#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>

#include "nweb.h"
#include "nweb_log.h"
#include "http_response.h"
#include "http_static_response.h"
#include "http_dynamic_response.h"

/* Resource Handler */
void handle_resource(request_rec* r) {
    int j, file_fd;

    /* open the file for reading */
    if(( file_fd = open(&r->uri[1],O_RDONLY)) == -1)
    	nweb_log(SORRY, "failed to open file",r->uri,r->fd);

    nweb_log(LOG,"SEND",r->uri,r->hit);

    /* response HTTP OK to the browser */
    (void)sprintf(r->buffer,"HTTP/1.0 200 OK\r\nContent-Type: %s\r\n\r\n", r->fstr);
    (void)write(r->fd,r->buffer,strlen(r->buffer));

	if (str_ends_with(r->uri, ".py") || str_ends_with(r->uri, ".php")) {
		handle_dynamic_resource(r, file_fd);
	} else {
		handle_static_resource(r, file_fd);
	}
}
